package com.bier.fishproject.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.json.JSONArray;
import org.json.JSONObject;
import com.bier.fishproject.R;
import com.bier.fishproject.activity.scan.ScanActivity;
import com.bier.fishproject.adapter.WaterListAdapter;
import com.bier.fishproject.entity.Infos;
import com.bier.fishproject.entity.Water;
import com.bier.fishproject.utils.Base64Str;
import com.bier.fishproject.utils.Constant;
import com.bier.fishproject.utils.GetLocation;
import com.bier.fishproject.utils.MyThreadPool;
import com.bier.fishproject.utils.Shared;
import com.bier.fishproject.utils.YLWWater;
import com.mining.app.zxing.view.CustomListView;
import com.mining.app.zxing.view.RoundView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
 * 首页
 * @author Administrator
 *
 */
public class MainActivity extends BaseActivity implements OnClickListener{

	private RelativeLayout rel;
	private TextView tvBalance,tvZcode,tvFcode,tvScan,tvAdd;
	private LinearLayout linBill;
	private CustomListView listViewY,listViewF;
	private String result;
	//true：主卡，false：副卡
	private boolean isZFCode=false;
	private List<Infos> listInfos=new ArrayList<Infos>();
	private List<Water> listY=new ArrayList<Water>();
	private List<Water> listF=new ArrayList<Water>();
	private Timer mTimer=null;
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);  
		initView();
	}
	
	/**
	 * 初始化方法
	 */
	private void initView(){
		rel=(RelativeLayout)findViewById(R.id.rel_am2);
		tvBalance=(TextView)findViewById(R.id.tv_am_balances);
		linBill=(LinearLayout)findViewById(R.id.lin_am_bill);
		tvZcode=(TextView)findViewById(R.id.tv_am_zcode);
		tvFcode=(TextView)findViewById(R.id.tv_am_fcode);
		RoundView rvy=(RoundView)findViewById(R.id.round_ac_y);
		RoundView rvf=(RoundView)findViewById(R.id.round_ac_f);
		rvy.setBackgroundColor(Color.BLUE);
		rvf.setBackgroundColor(Color.GREEN);
		listViewY=(CustomListView)findViewById(R.id.list_am_y);
		listViewF=(CustomListView)findViewById(R.id.list_am_f);
		tvScan=(TextView)findViewById(R.id.tv_am_scan);
		tvAdd=(TextView)findViewById(R.id.tv_am_add);
		rel.setOnClickListener(this);
		linBill.setOnClickListener(this);
		tvScan.setOnClickListener(this);
		tvAdd.setOnClickListener(this);
		Bundle bundle=getIntent().getExtras();
		if(bundle!=null){
			result=bundle.getString("date");
			if(!TextUtils.isEmpty(result)){
				try{
					final JSONObject json=new JSONObject(result);
					JSONArray ja=json.getJSONArray("infos");
					for (int i = 0,len=ja.length(); i < len; i++) {
						 JSONObject o=ja.getJSONObject(i);
						 Infos infos=new Infos();
						 infos.setCoffi(o.getString("coffi"));
						 infos.setCdealcount(o.getString("cdealcount"));
						 infos.setIname(o.getString("iname"));
						 infos.setStime(o.getString("stime"));
						 infos.setCdeal(o.getString("cdeal"));
						 infos.setIsex(o.getString("isex"));
						 infos.setCtype(o.getString("ctype"));
						 infos.setEtime(o.getString("etime"));
						 infos.setSuname(o.getString("suname"));
						 infos.setBala(o.getString("bala"));
						 infos.setIbirth(o.getString("ibirth"));
						 infos.setInum(o.getString("inum"));
						 infos.setInation(o.getString("ination"));
						 infos.setPn(o.getString("pn"));
						 infos.setCard(o.getString("card"));
						 infos.setAddr(o.getString("addr"));
						 listInfos.add(infos);
						 //判断登录账号是主卡，还是副卡
						 if(Shared.readString(getApplicationContext(), "code").equals(o.getString("card"))){
							 if(o.getString("ctype").equals("1")){
								 isZFCode=true;
							 }
						 }
						 //设置余额（显示主卡的余额）_与卡号
						 if(o.getString("ctype").equals("1")){
							 tvBalance.setText(o.getString("bala"));
							 tvZcode.setText("主卡："+o.getString("card"));
						 }else{
							 tvFcode.setText("副卡："+o.getString("card"));
						 }
					}
					if(isZFCode){
						tvFcode.setText("副卡："+(listInfos.size()-1)+"个");
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		 //查询可使用列表
		 mTimer = new Timer();
		 mTimer.scheduleAtFixedRate(new TimerTask() {
				public void run() {
					MyThreadPool.getInstent().submit(new Runnable() {
						public void run() {
							try {
								TTransport transport = new TSocket(Constant.IP, Constant.PORT, 5000);
								transport.open();
								TProtocol protocol = new TBinaryProtocol(transport);
								TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol, "YLWWater");
								YLWWater.Client client = new YLWWater.Client(mp1);
								String result=client.reqListOfDev(Shared.readString(getApplicationContext(), "code"));
								transport.close();
								if(!TextUtils.isEmpty(result)){
									final Message message=new Message();
									message.what=Constant.ONE;
									message.obj=result;
									handler.sendMessage(message);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					 });
				}
			}, 100, 10000);
	    //获取当前经纬度
		GetLocation.getIntesen().getLocation(getApplicationContext(), handler);
	}
	
	@SuppressLint("HandlerLeak") private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			endView();
			String result=msg.obj.toString();
			switch(msg.what){
			//获取使用列表
			case Constant.ONE:
				 listY.clear();
				 refresh(result,1);
				 break;
			//获取当前经纬度
			case Constant.TWO:
				 final String[] str=result.split("@");
				 if(null!=str && str.length>0){
					 MyThreadPool.getInstent().submit(new Runnable() {
							public void run() {
								try {
									TTransport transport = new TSocket(Constant.IP, Constant.PORT, 5000);
									transport.open();
									TProtocol protocol = new TBinaryProtocol(transport);
									TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol, "YLWWater");
									YLWWater.Client client = new YLWWater.Client(mp1);
									String result=client.reqListOfDevByLoc(Shared.readString(getApplicationContext(), "code"),Double.parseDouble(str[0]),Double.parseDouble(str[1]));
									transport.close();
									if(!TextUtils.isEmpty(result)){
										final Message message=new Message();
										message.what=Constant.THREE;
										message.obj=result;
										handler.sendMessage(message);
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						 });
				 }
				 break;
			case Constant.THREE:
				 listF.clear();
				 refresh(result,2);
				 break;
			default:
				 break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		Bundle bundle=new Bundle();
		switch(v.getId()){
		case R.id.rel_am2:
			 bundle.putSerializable("result",(Serializable) listInfos);
			 startActivity(CardListActivity.class, bundle);
			 break;
		//账单
		case R.id.lin_am_bill:
			 bundle.putSerializable("result",(Serializable) listInfos);
			 startActivity(BillListActivity.class, bundle);
			 break;
		//扫码加水
		case R.id.tv_am_scan:
			 startForResultActivity(ScanActivity.class, null, Constant.ONE);
			 break;
		//编号加水
		case R.id.tv_am_add:
			 View view=getLayoutInflater().inflate(R.layout.add_water, null);
			 bottomPopupWindow(0, 0, view);
			 final EditText et=(EditText)view.findViewById(R.id.et_aw_code);
			 final TextView tvSubmit=(TextView)view.findViewById(R.id.tv_aw_submit);
			 et.setInputType(EditorInfo.TYPE_CLASS_PHONE); 
			 et.addTextChangedListener(new TextWatcher() {
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				}
				public void beforeTextChanged(CharSequence s, int start, int count,int after) {
				}
				@SuppressLint("NewApi") public void afterTextChanged(Editable s) {
					if(s.toString().length()==4){
						tvSubmit.setClickable(true);
						tvSubmit.setBackground(getResources().getDrawable(R.drawable.login_textviews));
						tvSubmit.setOnClickListener(new View.OnClickListener() {
							public void onClick(View v) {
								Bundle bundle=new Bundle();
								bundle.putString("result", et.getText().toString().trim());
								startActivity(WaterDetailsActivity.class, bundle);
								mPopuwindow.dismiss();
							}
						});
					}else{
						tvSubmit.setClickable(false);
						tvSubmit.setBackground(getResources().getDrawable(R.drawable.login_textview));
					}
				}
			 });
		     break;
		default:
			 break;
		}
	}
	
	/**
	 * 刷新列表数据
	 * @param result
	 * @param type
	 */
	private void refresh(String result,int type){
		try{
			 final JSONObject json=new JSONObject(result);
			 if(json.getInt("status")==0){
				 JSONArray ja=json.getJSONArray("infos");
				 for (int i = 0,len=ja.length(); i < len; i++) {
					  JSONObject o=ja.getJSONObject(i);
					  Water water=new Water();
					  if(type==1){
						  water.setUsername(o.getString("username"));
					  }
					  water.setPseconde(o.getString("pseconde"));
					  water.setStone(o.getString("stone"));
					  water.setDstatus(o.getString("dstatus"));
					  water.setDustatus(o.getString("dustatus"));
					  water.setDid(o.getString("did"));
					  water.setUtime(o.getString("utime"));
					  water.setUtone(o.getString("utone"));
					  water.setPaytype(o.getString("paytype"));
					  water.setDeallimit(o.getString("deallimit"));
					  water.setDname(o.getString("dname"));
					  water.setMac(o.getString("mac"));
					  water.setStime(o.getString("stime"));
					  water.setSdelay(o.getString("sdelay"));
					  water.setDreading(o.getString("dreading"));
					  water.setTotal(o.getString("total"));
					  water.setEdelay(o.getString("edelay"));
					  if(type==1){
						  water.setCard(o.getString("card"));
					  }
					  water.setPtone(o.getString("ptone"));
					  if(type==1){
						  listY.add(water);
					  }else{
						  listF.add(water);
					  }
				}
				 if(type==1){
					 WaterListAdapter yAdapter=new WaterListAdapter(getApplicationContext(), listY);
					 listViewY.setAdapter(yAdapter);
					 listViewY.setDivider(null);
					 listViewY.setOnItemClickListener(new OnItemClickListener() {
						public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
							TextView tvCode=(TextView)arg1.findViewById(R.id.tv_wi_code);
							if(tvCode.getTag()!=null){
								Bundle bundle=new Bundle();
								bundle.putString("result", tvCode.getTag().toString());
								startActivity(WaterDetailsActivity.class, bundle);
							}
						}
					});
				 }else{
					 WaterListAdapter fAdapter=new WaterListAdapter(getApplicationContext(), listF);
					 listViewF.setAdapter(fAdapter);
					 listViewF.setDivider(null);
					 listViewF.setOnItemClickListener(new OnItemClickListener() {
							public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
								TextView tvCode=(TextView)arg1.findViewById(R.id.tv_wi_code);
								if(tvCode.getTag()!=null){
									Bundle bundle=new Bundle();
									bundle.putString("result", tvCode.getTag().toString());
									startActivity(WaterDetailsActivity.class, bundle);
								}
							}
						});
				 }
			 }else{
				 showShortToast(Base64Str.getFromBase64(json.getString("msg")));
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }
	}
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==Constant.ONE){
        	Bundle bundle = data.getExtras();
			if(bundle!=null){
				startActivity(WaterDetailsActivity.class, bundle);
			}
        }
	}
	
	@Override
	protected void onDestroy() {
		mTimer.cancel(); 
		if(GetLocation.getIntesen().locationClient!=null){
			GetLocation.getIntesen().locationClient.stopLocation();
		}
		super.onDestroy();
	}
}
